package com.zhihao.sdk.infrastructure.openai.impl;

import com.alibaba.fastjson2.JSON;
import com.zhihao.sdk.infrastructure.openai.IOpenAI;
import com.zhihao.sdk.infrastructure.openai.dto.ChatCompletionRequestDTO;
import com.zhihao.sdk.infrastructure.openai.dto.ChatCompletionSyncResponseDTO;
import com.zhihao.sdk.types.utils.BearerTokenUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * ChatGLM 模型
 */
public class ChatGLM implements IOpenAI {

    private final String apiHost; // API主机地址
    private final String apiKeySecret; // API密钥

    /**
     * 构造函数，初始化API主机地址和API密钥
     *
     * @param apiHost       API主机地址
     * @param apiKeySecret  API密钥
     */
    public ChatGLM(String apiHost, String apiKeySecret) {
        this.apiHost = apiHost;
        this.apiKeySecret = apiKeySecret;
    }

    @Override
    public ChatCompletionSyncResponseDTO completions(ChatCompletionRequestDTO requestDTO) throws Exception {
        // 获取Bearer Token，用于身份验证
        String token = BearerTokenUtils.getToken(apiKeySecret);

        // 创建URL对象并打开连接
        URL url = new URL(apiHost);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // 设置HTTP请求方法为POST
        connection.setRequestMethod("POST");

        // 设置请求头信息
        connection.setRequestProperty("Authorization", "Bearer " + token); // 身份验证令牌
        connection.setRequestProperty("Content-Type", "application/json"); // 请求内容类型为JSON
        connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); // 用户代理标识
        connection.setDoOutput(true); // 允许向服务器写入数据

        // 将请求体（ChatCompletionRequestDTO对象）转换为JSON字符串并写入输出流
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = JSON.toJSONString(requestDTO).getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        // 读取服务器返回的响应
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder content = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine);
        }

        // 关闭输入流并断开连接
        in.close();
        connection.disconnect();

        // 将响应内容解析为ChatCompletionSyncResponseDTO对象并返回
        return JSON.parseObject(content.toString(), ChatCompletionSyncResponseDTO.class);
    }

}